package reflectutils

import (
	"github.com/emirpasic/gods/maps/linkedhashmap"
	"github.com/sirupsen/logrus"
	"reflect"
)

const (
	TAG_GOCFG = "gocfg"

	TAG_ENV  = "env"
	TAG_JSON = "json"
	TAG_GODI = "godi"
	TAG_GROM = "gorm"
)

func ParseGocfgTag(v any) *linkedhashmap.Map {
	return Default().Parse(TAG_GOCFG, v).TagMap()
}

type ReflectTags struct {
	tagMap *linkedhashmap.Map `json:"tag_map"`
}

func Default() *ReflectTags {
	return &ReflectTags{
		tagMap: linkedhashmap.New(),
	}

}
func NewReflectTags() *ReflectTags {
	return Default()
}

func (this *ReflectTags) TagMap() *linkedhashmap.Map {
	return this.tagMap
}

func (this *ReflectTags) SetTagMap(tagMap *linkedhashmap.Map) {
	this.tagMap = tagMap
}

func (this *ReflectTags) ParseOne(v any, FieldName string, tagName string) {
	elem := reflect.TypeOf(v).Elem()

	structField, _ := elem.FieldByName(FieldName)
	this.tagMap.Put(FieldName, structField.Tag.Get(tagName))

}

func (this *ReflectTags) ToString() string {
	v, _ := this.tagMap.ToJSON()
	return string(v)
}

func (this *ReflectTags) Log() {

	this.tagMap.Each(func(key interface{}, value interface{}) {
		logrus.Info(key, value)
	})
	this.tagMap.Map(func(key1 interface{}, value1 interface{}) (interface{}, interface{}) {
		return key1, value1
	})
}

func (this *ReflectTags) ParseGorm(v any) {
	this.Parse(TAG_GROM, v)
}
func (this *ReflectTags) ParseJson(v any) {
	this.Parse(TAG_JSON, v)
}
func (this *ReflectTags) ParseEnv(v any) {
	this.Parse(TAG_ENV, v)
}
func (this *ReflectTags) ParseGocfgTag(v any) {
	this.Parse(TAG_GOCFG, v)
}

func (this *ReflectTags) Parse(key string, v any) *ReflectTags {
	elem := reflect.TypeOf(v).Elem()

	for i := 0; i < elem.NumField(); i++ {
		structField := elem.Field(i)
		var tag = structField.Tag.Get(key)
		if tag == "" {
			continue
		}

		this.tagMap.Put(structField.Name, tag)
		//logrus.Info(this.tagMap)
	}
	return this
}
